package cn.wolfcode.config;

import cn.wolfcode.domain.OrderInfo;
import cn.wolfcode.redis.SeckillRedisKey;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import top.javatool.canal.client.annotation.CanalTable;
import top.javatool.canal.client.handler.EntryHandler;

/**
 * @author zhenfeng
 * @Date 2021/5/17
 *
 * canal伪装为mysql从节点监听类
 */
@Slf4j
@CanalTable(value = "t_order_info")
@Component
public class OrderaInfoHandler implements EntryHandler<OrderInfo> {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public void insert(OrderInfo orderInfo) {
        log.info("监听到插入数据...");
        System.out.println(orderInfo);
        //下单成功插入订单后,将用户购买商品下单信息存在redis缓存中,防止重复下单
        redisTemplate.opsForSet().add(
                SeckillRedisKey.SECKILL_ORDER_SET.getRealKey(orderInfo.getSeckillTime() + ""),
                orderInfo.getUserId() + ":" + orderInfo.getSeckillId());
        //将订单信息缓存到redis中
        redisTemplate.opsForHash().put(SeckillRedisKey.SECKILL_ORDER_HASH.getRealKey(""),
                orderInfo.getOrderNo() + "", JSON.toJSONString(orderInfo));
    }
    @Override
    public void update(OrderInfo before, OrderInfo after) {
        log.info("监听到更新数据...");
        System.out.println(before);
        System.out.println(after);
        //数据库更新之后数据同步到redis中
        redisTemplate.opsForHash().put(SeckillRedisKey.SECKILL_ORDER_HASH.getRealKey(""),
                after.getOrderNo() + "", JSON.toJSONString(after));
    }
    @Override
    public void delete(OrderInfo orderInfo) {
        log.info("监听到删除数据...");
        System.out.println(orderInfo);
    }
}
